<?php

namespace app\tools;

use Yii;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Qiniu {
  //本地资源上传七牛
  public static  function putFileToQiniu($filePath) {
    //$filePath = str_replace('//', '', $filePath);
    $qiniu = Yii::$app->params['qiniu'];
    $bucket = $qiniu['bucket'];
    $url    = $qiniu['url'];
    $policy = [
      'saveKey' => '$(etag)$(ext)',
      'returnBody' => '{"key":$(key),"domain":"' . $url . '","size":$(fsize),"w": $(imageInfo.width),"h":$(imageInfo.height),"hash":$(etag)}'
    ];
    $auth = new Auth($qiniu['access_key'], $qiniu['secret_key']);
    $token = $auth->uploadToken($bucket, null, 3600, $policy);
    $uploadMgr = new UploadManager();
    list($res, $err) = $uploadMgr->putFile($token, null, $filePath);
    if($err == null) {
      unlink($filePath);
      return $res;
    }
  }

  //抓取远程资源上传七牛
  public static function fetchFileToQiniu($filePath) {
    //$filePath = str_replace('//', '', $filePath);
    $qiniu = Yii::$app->params['qiniu'];
    $auth = new Auth($qiniu['access_key'], $qiniu['secret_key']);
    $bucketMgr = new BucketManager($auth);
    list($res, $err) = $bucketMgr->fetch($filePath, $qiniu['bucket'], null);
    var_dump($err);die;
    if($err == null) {
      return $res;
    }
  }
}
